import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:go_router/go_router.dart';
import '../providers/comic_provider.dart';

class GenresScreen extends ConsumerStatefulWidget {
  const GenresScreen({super.key});

  @override
  ConsumerState<GenresScreen> createState() => _GenresScreenState();
}

class _GenresScreenState extends ConsumerState<GenresScreen> {
  bool _isExpanded = false;
  String _selectedGenre = 'All';
  String _selectedStatus = 'All';
  String _selectedPrice = 'All';
  String _selectedSort = 'All';

  // 基础分类标签
  static const List<String> _baseGenres = [
    'All',
    'Action',
    'Adventure',
    'Drama',
    'Magic',
    'Manhwa',
    'Martial Arts',
    'Seinen',
    'Fantasy',
    'Isekai',
    'Reincarnation',
    'Webtoon',
    'Super Power',
  ];

  // 扩展分类标签
  static const List<String> _expandedGenres = [
    'Romance',
    'Psychological',
    'Shounen',
    'Mature',
    'Mystery',
    'Supernatural',
    'Comedy',
    'Murim',
    'Overpowered',
    'Returner',
    'System',
    'Tragedy',
  ];

  static const List<String> _statusOptions = ['All', 'Ongoing', 'Completed'];
  static const List<String> _priceOptions = ['All', 'Free', 'Paid', 'Vip'];
  static const List<String> _sortOptions = ['All', 'Latest', 'Chapters'];

  @override
  Widget build(BuildContext context) {
    final comics = ref.watch(comicsProvider);

    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Column(
          children: [
            // 顶部标题栏
            Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  const Text(
                    'Genres',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                  const Spacer(),
                  IconButton(
                    onPressed: () {
                      // 搜索功能
                    },
                    icon: const Icon(
                      Icons.search,
                      color: Colors.teal,
                      size: 28,
                    ),
                  ),
                ],
              ),
            ),

            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 分类标签区域
                    _buildGenreTags(),

                    const SizedBox(height: 16),

                    // 状态筛选
                    _buildFilterSection(
                        'Status', _statusOptions, _selectedStatus, (value) {
                      setState(() {
                        _selectedStatus = value;
                      });
                    }),

                    const SizedBox(height: 16),

                    // 价格筛选
                    _buildFilterSection('Price', _priceOptions, _selectedPrice,
                        (value) {
                      setState(() {
                        _selectedPrice = value;
                      });
                    }),

                    const SizedBox(height: 16),

                    // 排序筛选
                    _buildFilterSection('Sort', _sortOptions, _selectedSort,
                        (value) {
                      setState(() {
                        _selectedSort = value;
                      });
                    }),

                    const SizedBox(height: 24),

                    // 刷新指示器
                    const Center(
                      child: SizedBox(
                        width: 24,
                        height: 24,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: Colors.teal,
                        ),
                      ),
                    ),

                    const SizedBox(height: 24),

                    // 漫画网格
                    _buildComicsGrid(comics),

                    const SizedBox(height: 20),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildGenreTags() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 所有标签（基础 + 扩展如果展开）
          Wrap(
            spacing: 12,
            runSpacing: 12,
            children: [
              // 基础标签
              ..._baseGenres.map((genre) => _buildGenreTag(genre)),
              // 扩展标签（如果展开）
              if (_isExpanded)
                ..._expandedGenres.map((genre) => _buildGenreTag(genre)),
            ],
          ),

          // 展开/收起按钮
          const SizedBox(height: 16),
          Row(
            children: [
              const Spacer(),
              GestureDetector(
                onTap: () {
                  setState(() {
                    _isExpanded = !_isExpanded;
                  });
                },
                child: Text(
                  _isExpanded ? 'Collapse' : 'Expand',
                  style: const TextStyle(
                    color: Colors.teal,
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildGenreTag(String genre) {
    final isSelected = genre == _selectedGenre;

    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedGenre = genre;
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: isSelected
            ? BoxDecoration(
                color: Colors.teal,
                borderRadius: BorderRadius.circular(20),
              )
            : null,
        child: Text(
          genre,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.grey[600],
            fontSize: 14,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
    );
  }

  Widget _buildFilterSection(String title, List<String> options,
      String selected, Function(String) onChanged) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Wrap(
        spacing: 12,
        runSpacing: 12,
        children: options.map((option) {
          final isSelected = option == selected;
          return GestureDetector(
            onTap: () => onChanged(option),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: isSelected
                  ? BoxDecoration(
                      color: Colors.teal,
                      borderRadius: BorderRadius.circular(20),
                    )
                  : null,
              child: Text(
                option,
                style: TextStyle(
                  color: isSelected ? Colors.white : Colors.grey[600],
                  fontSize: 14,
                  fontWeight: FontWeight.normal,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildComicsGrid(List<dynamic> comics) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          childAspectRatio: 0.65,
          crossAxisSpacing: 12,
          mainAxisSpacing: 16,
        ),
        itemCount: comics.length,
        itemBuilder: (context, index) {
          final comic = comics[index];
          return _buildComicCard(comic);
        },
      ),
    );
  }

  Widget _buildComicCard(dynamic comic) {
    return GestureDetector(
      onTap: () => context.push('/comic/${comic.id}'),
      child: Column(
        children: [
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: CachedNetworkImage(
                imageUrl: comic.coverImageUrl,
                fit: BoxFit.cover,
                width: double.infinity,
                placeholder: (context, url) => Container(
                  color: Colors.grey[200],
                ),
                errorWidget: (context, url, error) => Container(
                  color: Colors.grey[200],
                  child: const Icon(Icons.error),
                ),
              ),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            comic.title,
            style: const TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Colors.black87,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}
